# -*- coding;utf-8 -*-
"""
File name : RecognizeEduPaperCutBaidu.PY
Program IDE : PyCharm
Create file time: 2024/7/16 15:30
File Create By Author : 朱清闯
"""
import base64
import urllib
import requests
from django.conf import settings
from django.core.cache import cache


API_KEY = settings.BAIDU_OCR_ACCESS_KEY
SECRET_KEY = settings.BAIDU_OCR_ACCESS_SECRET


def main(file):
    request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/formula?access_token=" + get_access_token()
    params = {"image": file, 'disp_formula': True}
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'application/json'
    }
    response = requests.post(request_url, data=params, headers=headers)
    print(response.json())
    return response.json()


def get_access_token():
    """
    使用 AK，SK 生成鉴权签名（Access Token）
    :return: access_token，或是None(如果错误)
    """
    cache_access_token = cache.get('BAIDU_OCR_ACCESS_TOKEN')
    if cache_access_token and len(cache_access_token) > 0:
        return cache_access_token
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}
    cache_access_token = str(requests.post(url, params=params).json().get("access_token"))
    cache.set('BAIDU_OCR_ACCESS_TOKEN', cache_access_token, 29 * 60 * 60)
    return cache_access_token


def get_file_content_as_base64(path, urlencoded=False):
    """
    获取文件base64编码
    :param path: 文件路径
    :param urlencoded: 是否对结果进行urlencoded
    :return: base64编码信息
    """
    with open(path, "rb") as f:
        content = base64.b64encode(f.read()).decode("utf8")
        if urlencoded:
            content = urllib.parse.quote_plus(content)
    return content